
package cn.fulong.sso.client.utils;


import java.io.UnsupportedEncodingException;

public class Base64Util {
    public static String decode(final String encodedText) {
        try {
            final byte[] textByte = Base64.base64ToByteArray(encodedText);
            return new String(textByte, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 二进制数据编码为BASE64字符串
     *
     * @param text
     * @return
     * @throws Exception
     */
    public static String encode(final String text) {
        try {
            final byte[] textByte = text.getBytes("UTF-8");
            return Base64.byteArrayToBase64(textByte);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param formUrl
     * @return 判断url是被Base64编码
     */
    public static boolean isBase64Url(String formUrl) {
        if (StringSelfUtil.isBlank(formUrl)) {
            return false;
        }
        if (formUrl.startsWith("http:") || formUrl.startsWith("https:")) {
            return false;
        }
        return true;
    }


    public static String base64ToUrlEncode(String base64Url) {
        if (Base64Util.isBase64Url(base64Url)) {
            String decodeUrl = Base64Util.decode(base64Url);
            return URLCoderUtil.encode(decodeUrl);
        }
        return base64Url;
    }

    public static String urlEncodeToBase64(String encodeUrl) {
        if (Base64Util.isBase64Url(encodeUrl)) {
            return encodeUrl;
        }
        String decodeUrl = URLCoderUtil.decode(encodeUrl);
        return Base64Util.encode(decodeUrl);
    }

}
